const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')

const app = new Koa()
// router
// const userInterface = require('./interface/user')

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(app.env === 'production')

// 引入mongoose redis 
import mongoose from 'mongoose'
// 处理passport相关请求 
import bodyParser from 'koa-bodyparser'
// session删写
import session from 'koa-generic-session'
import Redis from 'koa-redis'
// 代码格式化. 打印.
import json from 'koa-json'
import dbsConfig from './dbs/config'
import UserInterface from './interface/user'
import GeoInterface from './interface/geo'
import searchInterface from './interface/search'
import categroyInterface from './interface/category'
import cartInterface from './interface/cart'
import passport from './interface/utils/passport'
// session加密处理的两字符
app.keys = ['keys','key']
app.proxy = true
// 存储
app.use(session({
  key: 'egg-mt',
  prefix: 'mt:uid',
  store: new Redis()
}))
app.use(bodyParser({
  enbleTypes: ['text','json','form']
}))
app.use(json())
// 连接数据库
mongoose.connect(dbsConfig.dbs, {
  useNewUrlParser: true
})
app.use(passport.initialize())
app.use(passport.session())

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const { 
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  // 使用路由
  app.use(searchInterface.routes()).use(searchInterface.allowedMethods())
  app.use(UserInterface.routes()).use(UserInterface.allowedMethods())
  app.use(GeoInterface.routes()).use(GeoInterface.allowedMethods())
  app.use(categroyInterface.routes()).use(categroyInterface.allowedMethods())
  app.use(cartInterface.routes()).use(cartInterface.allowedMethods())

  app.use(ctx => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })
  

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
